package en.kaist.cs408.acav;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import en.kaist.cs408.R;
import en.kaist.cs408.acav.CreateClass.NetworkHandler;

public class AttendanceList extends Activity implements OnItemLongClickListener {

	private ListView studentList;
	// alert dialog displayed to check attendance manually
	private AlertDialog alertDialog;
	MyAdapter mAdapter;
	// variable which get the selected student for the OnLongClickItem event
	private int mPosition;
	private DatePicker mDatepicker;
	private Button mSearch;
	private EditText tvDisplayDate;
	private DatePicker dpResult;
	private Button btnChangeDate;

	private int year;
	private int month;
	private int day;

	String courseID;
	String studentID;
	String password;
	String pwdEncrypt;
	String date;
	boolean beforeValue;
	boolean afterValue;
	
	static final int DATE_DIALOG_ID = 999;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.attendancelist);

		
		mAdapter = new MyAdapter(new ArrayList<Student>(), this);
		//mAdapter.testData();
		studentList = (ListView) findViewById(R.id.studentListView);
		studentList.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				mPosition = position;
				studentID = mAdapter.getItem(mPosition).getId();
				beforeValue = mAdapter.getItem(mPosition).getAttendance();
				initAlertDialog();
				return false;
			}

		});

		studentList.setAdapter(mAdapter);
		
		
		mSearch = (Button) findViewById(R.id.buttonSearch);
		setCurrentDateOnView();
		addListenerOnButton();

		mSearch.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/* Check the input's verification */
				Verifier createClassVerifier = new Verifier();

				EditText cidEditText = (EditText) findViewById(R.id.attendance_courseID);
				courseID = cidEditText.getText().toString();

				EditText pwdEditText = (EditText) findViewById(R.id.attendance_PWD);
				password = pwdEditText.getText().toString();

				boolean cid_result = createClassVerifier
						.verifyCourseID(courseID);
				int pwd_result = createClassVerifier.verifyPassword(password);

				if (cid_result == false) {
					Toast.makeText(AttendanceList.this,
							"Course ID in WRONG format", Toast.LENGTH_LONG)
							.show();
					cidEditText.requestFocus();
				} else if (pwd_result == -2) {
					Toast.makeText(AttendanceList.this,
							"Password should be 8 ~ 20 letters",
							Toast.LENGTH_LONG).show();
					pwdEditText.requestFocus();
				} else {
					//Date date = getDateFromDatePicket(mDatepicker);
					
					EditText dateEditText = (EditText) findViewById(R.id.tvDate);
					date = dateEditText.getText().toString();
					
					mAdapter.clear();
					/*
					 * Send to Server (DB update will be occurred in Server-side
					 * code)
					 */
					SHAEncryption sha = new SHAEncryption(); 
					pwdEncrypt = sha.encryptSHA256(password);
					
					NetworkHandler handler = new NetworkHandler(){
						public void handleMessage(Message msg){
							switch (msg.what){
							case 0:
								if (mAdapter.getCount() != 0)
									Toast.makeText(AttendanceList.this, "List UP!!", Toast.LENGTH_LONG).show();
								else
									Toast.makeText(AttendanceList.this, "No result found on this date", Toast.LENGTH_LONG).show();
								
								mAdapter.notifyDataSetChanged();
								break;
							case -1:
								Toast.makeText(AttendanceList.this, "Wrong Course ID or Password", Toast.LENGTH_LONG).show();
								break;
							default:
								Toast.makeText(AttendanceList.this, "Exception Occurred", Toast.LENGTH_LONG).show();
								break;	
							}
						}
					};
					
					NetworkThread nt = new NetworkThread(4000, courseID, null, pwdEncrypt, null, null, date, mAdapter, false, handler);
					nt.start();
					
					Toast.makeText(AttendanceList.this,
							"Send Info to server..", Toast.LENGTH_LONG).show();
				}

			};
		});

		
	}

	// display current date
	public void setCurrentDateOnView() {

		tvDisplayDate = (EditText) findViewById(R.id.tvDate);
		//dpResult = (DatePicker) findViewById(R.id.dpResult);

		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);

		// set current date into textview
		tvDisplayDate.setText(new StringBuilder()
				// Month is 0 based, just add 1
			.append(year).append("-").append(String.format("%02d", month + 1)).append("-").append(String.format("%02d", day))
				.append(" "));
		
		// set current date into datepicker
		// dpResult.init(year, month, day, null);

	}

	public void addListenerOnButton() {

		TextView tv = (TextView) findViewById(R.id.tvDate);
		tv.setInputType(InputType.TYPE_NULL);
		
		tv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus){
					Dialog d = onCreateDialog(DATE_DIALOG_ID);
					d.show();
				}
			}
		});
		
		tv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// showDialog(DATE_DIALOG_ID);
				Dialog d = onCreateDialog(DATE_DIALOG_ID);
				d.show();
			}

		});
		
	
	/*	
		tv.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				// showDialog(DATE_DIALOG_ID);
				Dialog d = onCreateDialog(DATE_DIALOG_ID);
				d.show();
				return false;
			}

		});
		*/
		
		/*
		 * btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
		 * 
		 * btnChangeDate.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) {
		 * 
		 * showDialog(DATE_DIALOG_ID);
		 * 
		 * }
		 * 
		 * });
		 */
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			// set date picker as current date
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			// set selected date into textview
			tvDisplayDate.setText(new StringBuilder().append(year).append("-").append(String.format("%02d", month + 1))
					.append("-").append(String.format("%02d", day))
					.append(" "));

			// set selected date into datepicker also
			//dpResult.init(year, month, day, null);

		}
	};

	/**
	 * Initiate the pop-up which will be displayed to check attendance manually
	 */
	private void initAlertDialog() {
		alertDialog = new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("Check attendance manually")
				.setMessage(
						"Do you want to check attendance manually for student: "
								+ "\n" + "\"" + studentID + "\"" + " ?")
				.setNegativeButton("No", null)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								// db.supprimerUnePhrase(nomDuPatient,
								// mlistAdapt.getItem(mPosition));
								// mlistAdapt.remove(mlistAdapt.getItem(mPosition));
								// mlistAdapt.notifyDataSetChanged();
								// mPosition = -1; 
								
								afterValue = true;
								if (beforeValue == true) afterValue = false;
								
								NetworkHandler handler = new NetworkHandler(){
									public void handleMessage(Message msg){
										switch (msg.what){
										case 0:
											// Success
											mAdapter.getItem(mPosition).attendance = afterValue;
											mAdapter.notifyDataSetChanged();
											Toast.makeText(AttendanceList.this,
													"Manual checking success!", Toast.LENGTH_LONG)
													.show();
											break;
										case -1:
											// Fail
											Toast.makeText(AttendanceList.this,
													"Manual checking failed", Toast.LENGTH_LONG)
													.show();
											break;
										default:
											// SQLException
											Toast.makeText(AttendanceList.this,
													"SQLException occurred", Toast.LENGTH_LONG)
													.show();
											break;	
										}
									}
								};
								
								NetworkThread nt = new NetworkThread(5000, courseID, studentID, null, null, null, date, null, afterValue, handler);
								nt.start();
								
							}
						}).create();
		alertDialog.show();
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		// TODO Auto-generated method stub
		return false;
	}

	public Date getDateFromDatePicket(DatePicker datePicker) {
		int day = datePicker.getDayOfMonth();
		int month = datePicker.getMonth();
		int year = datePicker.getYear();

		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, day);

		return calendar.getTime();
	}

}